<?php
/**
 * author      :chenwenwen
 * createTime  :2020-04-12 15:59
 * description :
 */
declare(strict_types=1);//严格模式

namespace app\common\lib\sms;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use think\facade\Log;

class AliSms implements SmsBase {

    /**
     * 阿里云发送短信验证码
     * @param string $phone
     * @param int $code
     * @return bool
     * @throws ClientException
     */
    public static function sendCode(string $phone, int $code): bool {
        AlibabaCloud::accessKeyClient(config('aliyun.access_key'), config('aliyun.access_secret'))
            ->regionId(config('aliyun.region_id'))
            ->asDefaultClient();

        $templateParam = [$code];

        try {
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                // ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->host(config('aliyun.host'))
                ->options([
                    'query' => [
                        'RegionId' => config('aliyun.region_id'),
                        'PhoneNumbers' => $phone,
                        'SignName' => config('aliyun.sign_name'),
                        'TemplateCode' => config('aliyun.template_code'),
                        'TemplaetParam'=>json_encode($templateParam)
                    ],
                ])
                ->request();
            Log::info("alisms-sendCode-{$phone}-result:" . json_encode($result->toArray()));
            //print_r($result->toArray());
        } catch (ClientException $e) {
            //echo $e->getErrorMessage() . PHP_EOL; //日志记录
            Log::info("alisms-sendCode-{$phone}-ClientException:" . $e->getErrorMessage());
            return false;
        } catch (ServerException $e) {
            //echo $e->getErrorMessage() . PHP_EOL;
            Log::info("alisms-sendCode-{$phone}-ServerException:" . $e->getErrorMessage());
            return false;
        }
        return true;
    }
}